package com.phiture.erp.basic.common.utils;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YH
 * @date 2025/3/31
 */
@Component
public class BasicCodeGenerator {

    private static RedissonClient redissonClient;

    @Autowired
    public BasicCodeGenerator(RedissonClient redissonClient) {
        BasicCodeGenerator.redissonClient = redissonClient;
    }
    private final static String CUSTOMER_CODE_SEQ_KEY = "customer:code:seq";
    private final static String SUPPLIER_CODE_SEQ_KEY = "supplier:code:seq";
    private final static String CUSTOMER_CODE_PREFIX = "CUS-";
    private final static String SUPPLIER_CODE_PREFIX = "SUP-";

    /**
     * 客户编码
     */
    public static String generateCustomerCode() {
        return generate(CUSTOMER_CODE_SEQ_KEY, CUSTOMER_CODE_PREFIX);
    }

    /**
     * 供应商编码
     */
    public static String generateSupplierCode() {
        return generate(SUPPLIER_CODE_SEQ_KEY, SUPPLIER_CODE_PREFIX);
    }

    /**
     * 批量客户编码
     */
    public static List<String> batchGenerateCustomerCode(int count) {
        return batchGenerate(count, CUSTOMER_CODE_SEQ_KEY, CUSTOMER_CODE_PREFIX);
    }

    /**
     * 批量供应商编码
     */
    public static List<String> batchGenerateSupplierCode(int count) {
        return batchGenerate(count, SUPPLIER_CODE_SEQ_KEY, SUPPLIER_CODE_PREFIX);
    }

    private static String generate(String cacheKey, String prefix){
        if (redissonClient == null) {
            throw new IllegalStateException("RedissonClient 未初始化");
        }
        // 获取分布式原子计数器
        RAtomicLong counter = redissonClient.getAtomicLong(cacheKey);
        // 原子性递增并获取值
        long seq = counter.incrementAndGet();
        return prefix + String.format("%04d", seq);
    }

    public static List<String> batchGenerate(int count, String cacheKey, String prefix) {
        if (redissonClient == null) {
            throw new IllegalStateException("RedissonClient 未初始化");
        }
        RAtomicLong counter = redissonClient.getAtomicLong(cacheKey);
        // 使用getAndAdd实现批量获取序列范围
        long startSeq = counter.getAndAdd(count);
        List<String> codes = new ArrayList<>(count);
        for (int i = 1; i <= count; i++) {
            codes.add(prefix + String.format("%04d", startSeq + i));
        }
        return codes;
    }
}
